﻿'use client'

import { useState } from 'react'
import { SortAsc, SortDesc, RotateCcw, Copy } from 'lucide-react'

export default function LineSorterPage() {
  const [input, setInput] = useState('')
  const [output, setOutput] = useState('')
  const [sortType, setSortType] = useState('asc')
  const [caseSensitive, setCaseSensitive] = useState(false)
  const [removeEmpty, setRemoveEmpty] = useState(true)
  const [removeDuplicates, setRemoveDuplicates] = useState(false)

  const sortLines = (text: string): string => {
    if (!text.trim()) return ''
    
    let lines = text.split('\n')
    
    // 移除空行
    if (removeEmpty) {
      lines = lines.filter(line => line.trim() !== '')
    }
    
    // 移除重复行
    if (removeDuplicates) {
      lines = [...new Set(lines)]
    }
    
    // 排序
    lines.sort((a, b) => {
      let compareA = caseSensitive ? a : a.toLowerCase()
      let compareB = caseSensitive ? b : b.toLowerCase()
      
      if (sortType === 'asc') {
        return compareA.localeCompare(compareB)
      } else if (sortType === 'desc') {
        return compareB.localeCompare(compareA)
      } else if (sortType === 'length') {
        return a.length - b.length
      } else if (sortType === 'lengthDesc') {
        return b.length - a.length
      } else if (sortType === 'random') {
        return Math.random() - 0.5
      } else if (sortType === 'reverse') {
        return 0 // 不排序，只反转
      }
      return 0
    })
    
    // 反转顺序（用于reverse选项）
    if (sortType === 'reverse') {
      lines = text.split('\n').reverse()
      if (removeEmpty) {
        lines = lines.filter(line => line.trim() !== '')
      }
    }
    
    return lines.join('\n')
  }

  const handleSort = () => {
    const sorted = sortLines(input)
    setOutput(sorted)
  }

  const handleInputChange = (value: string) => {
    setInput(value)
    if (value.trim()) {
      const sorted = sortLines(value)
      setOutput(sorted)
    } else {
      setOutput('')
    }
  }

  const copyToClipboard = () => {
    navigator.clipboard?.writeText(output)
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-4xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">行排序工具</h1>
          <p className="text-gray-600">对文本行进行各种排序操作，支持多种排序方式</p>
        </div>

        <div className="mb-6 flex gap-4">
          <button
            onClick={handleSort}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
          >
            <SortAsc className="w-4 h-4" />
            排序文本
          </button>
          <button
            onClick={copyToClipboard}
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
          >
            <Copy className="w-4 h-4" />
            复制结果
          </button>
          <button
            onClick={() => { setInput(''); setOutput('') }}
            className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 flex items-center gap-2"
          >
            <RotateCcw className="w-4 h-4" />
            清空
          </button>
        </div>

        <div className="mb-6 bg-white p-4 rounded-lg border border-gray-200">
          <h4 className="font-medium text-gray-900 mb-3">排序选项</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">排序方式</label>
              <select
                value={sortType}
                onChange={(e) => {
                  setSortType(e.target.value)
                  if (input.trim()) {
                    setTimeout(() => handleSort(), 100)
                  }
                }}
                className="w-full p-2 border border-gray-300 rounded-md"
              >
                <option value="asc">字母升序 (A-Z)</option>
                <option value="desc">字母降序 (Z-A)</option>
                <option value="length">按长度升序</option>
                <option value="lengthDesc">按长度降序</option>
                <option value="random">随机排序</option>
                <option value="reverse">反转顺序</option>
              </select>
            </div>
          </div>
          
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <label className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={caseSensitive}
                onChange={(e) => {
                  setCaseSensitive(e.target.checked)
                  if (input.trim()) {
                    setTimeout(() => handleSort(), 100)
                  }
                }}
                className="w-4 h-4 text-blue-600 border-gray-300 rounded"
              />
              <span className="text-sm">区分大小写</span>
            </label>
            <label className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={removeEmpty}
                onChange={(e) => {
                  setRemoveEmpty(e.target.checked)
                  if (input.trim()) {
                    setTimeout(() => handleSort(), 100)
                  }
                }}
                className="w-4 h-4 text-blue-600 border-gray-300 rounded"
              />
              <span className="text-sm">移除空行</span>
            </label>
            <label className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={removeDuplicates}
                onChange={(e) => {
                  setRemoveDuplicates(e.target.checked)
                  if (input.trim()) {
                    setTimeout(() => handleSort(), 100)
                  }
                }}
                className="w-4 h-4 text-blue-600 border-gray-300 rounded"
              />
              <span className="text-sm">移除重复行</span>
            </label>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700">输入文本 (每行一项)</label>
            <textarea
              value={input}
              onChange={(e) => handleInputChange(e.target.value)}
              placeholder="输入要排序的文本，每行一项..."
              rows={12}
              className="w-full p-3 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700">排序结果</label>
            <textarea
              value={output}
              readOnly
              rows={12}
              className="w-full p-3 border border-gray-300 rounded-lg bg-gray-50 resize-none"
              placeholder="排序后的文本将在这里显示..."
            />
          </div>
        </div>

        <div className="mt-8 bg-gray-50 p-4 rounded-lg">
          <h4 className="font-medium text-gray-900 mb-2">示例数据</h4>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <button
              onClick={() => handleInputChange('apple\nbanana\ncherry\ndate\nelderberry')}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">水果列表</div>
              <div className="text-xs text-gray-500 mt-1">apple, banana, cherry...</div>
            </button>
            <button
              onClick={() => handleInputChange('张三\n李四\n王五\n赵六\n钱七')}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">中文姓名</div>
              <div className="text-xs text-gray-500 mt-1">张三, 李四, 王五...</div>
            </button>
            <button
              onClick={() => handleInputChange('1. 第一项\n2. 第二项\n3. 第三项\n4. 第四项\n5. 第五项')}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">编号列表</div>
              <div className="text-xs text-gray-500 mt-1">1. 第一项, 2. 第二项...</div>
            </button>
          </div>
        </div>

        <div className="mt-6 bg-blue-50 p-4 rounded-lg">
          <h4 className="font-medium text-blue-900 mb-2">排序方式说明</h4>
          <ul className="text-blue-800 text-sm space-y-1">
            <li>• <strong>字母升序:</strong> 按字母顺序从A到Z排序</li>
            <li>• <strong>字母降序:</strong> 按字母顺序从Z到A排序</li>
            <li>• <strong>按长度升序:</strong> 按文本长度从短到长排序</li>
            <li>• <strong>按长度降序:</strong> 按文本长度从长到短排序</li>
            <li>• <strong>随机排序:</strong> 随机打乱行的顺序</li>
            <li>• <strong>反转顺序:</strong> 将原有顺序完全反转</li>
          </ul>
        </div>
      </div>
    </div>
  )
}
